﻿package crochet.core;

/*
 Copyright 2011 Intuitive Solutions

 Licensed under the Apache License, Version 2.0 (the "License");
 you may not use this file except in compliance with the License.
 You may obtain a copy of the License at

 http://www.apache.org/licenses/LICENSE-2.0

 Unless required by applicable law or agreed to in writing, software
 distributed under the License is distributed on an "AS IS" BASIS,
 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 See the License for the specific language governing permissions and
 limitations under the License.
 */

import crochet.core.configuration.CrochetConfiguration;
import crochet.core.policy.ExecutionPolicyFactory;

import crochet.core.policy.IExecutionPolicy;

public class SchedulerFactory {
	private static SchedulerFactory sfInstance = null;

	protected SchedulerFactory() {
	}

	public static SchedulerFactory getInstance() {
		if (sfInstance == null) {
			sfInstance = new SchedulerFactory();
		}

		return sfInstance;
	}

	public IScheduler CreateScheduler(SchedulerType stSchedulerType,
			String sName) {
		return CreateScheduler(stSchedulerType,
				GetParams(stSchedulerType, sName));
	}

	public IScheduler CreateScheduler(SchedulerType stSchedulerType,
			Object... oaParams) {
		IScheduler sScheduler = null;

		IExecutionPolicy epExecutionPolicy = ExecutionPolicyFactory
				.getInstance().Create(
						oaParams != null ? (String) oaParams[1] : "", null,
						null);

		switch (stSchedulerType) {
		case TimerPool:
			sScheduler = new TimerPoolScheduler((Integer) oaParams[2],
					(Boolean) oaParams[3], (Integer) oaParams[4],
					epExecutionPolicy);
			break;
		case Immediate:
			sScheduler = new ImmediateScheduler(epExecutionPolicy);
			break;
		case ThreadPool:
			sScheduler = new ThreadPoolScheduler((Integer) oaParams[2],
					epExecutionPolicy);
			break;
		case Sequential:
			sScheduler = new SequentialScheduler(epExecutionPolicy);
			break;
		case ExecutionPool:
			sScheduler = new ExecutionPoolScheduler((Integer) oaParams[2],
					epExecutionPolicy);
			break;
		default:
			break;
		}

		return sScheduler;
	}

	public Object[] GetParams(SchedulerType stSchedulerType, String sName) {
		Object[] oParams = null;

		switch (stSchedulerType) {
		/*
		 * case TimerPool: oParams =
		 * CrochetConfiguration.getInstance().getTimerSchedulers
		 * (sName).GetAttributes(); break;
		 */
		case Immediate:
			oParams = CrochetConfiguration.getInstance()
					.getImmediateSchedulers(sName).GetAttributes();
			break;
		case ThreadPool:
			oParams = CrochetConfiguration.getInstance()
					.getThreadPoolSchedulers(sName).GetAttributes();
			break;
		case ExecutionPool:
			oParams = CrochetConfiguration.getInstance()
					.getExecutionPoolSchedulers(sName).GetAttributes();
			break;
		default:
			break;
		}

		return oParams;
	}
}
